package cn.ug.pay.utils;

import cn.ug.config.YeePayConfig;
import cn.ug.pay.bean.request.TradeCommonParamBean;
import cn.ug.pay.bean.status.CommonConstants;
import cn.ug.pay.pay.yeepay.AES;
import cn.ug.pay.pay.yeepay.RSA;
import cn.ug.pay.pay.yeepay.RandomUtil;
import cn.ug.pay.pay.yeepay.TZTService;
import cn.ug.util.UF;
import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 *  发起请求
 *  @auther ywl
 *  @date 2018-01-31 11:31:20
 */
@Component
public class RequestUtil {
	
	private static Logger logger = LoggerFactory.getLogger(RequestUtil.class);

	@Resource
	private YeePayConfig yeePayConfig;

	@Resource
	private TZTService tZTService;

	/**
	 * 发送HTTP请求
	 * @param url 请求地址
	 * @param dataMap 请求数据
	 * @return
	 */
	public  Map<String, String> sendYeePayHttp(String url,TreeMap<String,String> dataMap) {
		Map<String, String> result = new HashMap<String, String>();
		String customError	= "";	//自定义，非接口返回
		String merchantAESKey		= getMerchantAESKey();   //商户密钥
		String yeepayPublicKey		= yeePayConfig.getYeepayPublicKey();       //易宝公钥
		HttpClient httpClient	    = new HttpClient();
		PostMethod postMethod		= new PostMethod(url);
		try {
			String jsonStr			= JSON.toJSONString(dataMap);
			String data				= AES.encryptToBase64(jsonStr, merchantAESKey);
			String encryptkey		= RSA.encrypt(merchantAESKey, yeepayPublicKey);

			System.out.println("data=" + data);
			System.out.println("encryptkey=" + encryptkey);

			NameValuePair[] datas		= {new NameValuePair("merchantno", dataMap.get("merchantno")),
					new NameValuePair("data", data),
					new NameValuePair("encryptkey", encryptkey)};

			postMethod.setRequestBody(datas);

			int statusCode				= httpClient.executeMethod(postMethod);
			byte[] responseByte			= postMethod.getResponseBody();
			String responseBody			= new String(responseByte, "UTF-8");

			result = tZTService.parseHttpResponseBody(statusCode, responseBody);
		} catch(Exception e) {
			logger.info("异常原因!" + e.toString());
			//e.printStackTrace();
		} finally {
			postMethod.releaseConnection();
		}
		return result;
	}
	/**
	 * 取得商户AESKey
	 */
	public static String getMerchantAESKey() {
		return (RandomUtil.getRandom(16));
	}

	/**
	 * 支付公共请求数据组装
	 * @param paramBean
	 * @param  paramBean 交易参数
	 * @return
	 */
	public  TreeMap<String, String> getRequestParam(TradeCommonParamBean paramBean){
		TreeMap<String, String> dataMap	= new TreeMap<String, String>();
		dataMap.put("merchantno",   yeePayConfig.getMerchantAccount());
		dataMap.put("requestno",    paramBean.getOrderId());
		dataMap.put("identityid", 	  paramBean.getBankCardBean().getRequestNo());
		dataMap.put("identitytype", CommonConstants.USER_ID);
		dataMap.put("amount", 	      paramBean.getAmount().toString());
		dataMap.put("productname",  paramBean.getTitle());
		dataMap.put("avaliabletime", "10");
		dataMap.put("cardtop", 	  paramBean.getBankCardBean().getCardTop()+"");
		dataMap.put("cardlast", 	  paramBean.getBankCardBean().getCardLast()+"");
		dataMap.put("terminalid", 	  CommonConstants.ID_CODE);
		dataMap.put("registtime", 	  UF.getFormatDateTime(LocalDateTime.now()));
		dataMap.put("lastloginterminalid", CommonConstants.ID_CODE);
		dataMap.put("issetpaypwd",  "0");
		dataMap.put("callbackurl",  paramBean.getCallBackUrl());
		dataMap.put("requesttime",  UF.getFormatDateTime(LocalDateTime.now()));
		dataMap.put("sign",          tZTService.getSign(dataMap));
		return dataMap;
	}
}
